/*
 * Copyright 2013 NJUT  qixiaobo. All rights reserved.
 */
package com.fujitsu.nanjing.mobile.common;

import java.io.File;
import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.tools.generic.DateTool;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Component;
import org.springframework.ui.velocity.VelocityEngineUtils;

@Component
public class ThirdVelocityEmailService {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger
            .getLogger(ThirdVelocityEmailService.class);

    @Resource
    private JavaMailSender mailSender;
    @Resource
    private VelocityEngine velocityEngine;

    public void sendEmail(Map<String, Object> map, final String subject,
            final String vmfile, final String[] mailTo, final String[] files) {
        final Map<String, Object> model = putTool(map);
        MimeMessagePreparator preparator = new MimeMessagePreparator() {
            // 注意MimeMessagePreparator接口只有这一个回调函数
            @Override
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage,
                        true, "utf-8");
                // 这是一个生成Mime邮件简单工具，如果不使用GBK这个，中文会出现乱码
                // 如果您使用的都是英文，那么可以使用MimeMessageHelper message = new
                // MimeMessageHelper(mimeMessage);
                message.setTo(mailTo);// 设置接收方的email地址
                message.setSubject(subject);// 设置邮件主题
                message.setFrom("q13073451412@163.com");// 设置发送方地址
                String text = VelocityEngineUtils.mergeTemplateIntoString(
                        velocityEngine, vmfile, "utf-8", model);
                // 从模板中加载要发送的内容，vmfile就是模板文件的名字
                // 注意模板中有中文要加GBK，model中存放的是要替换模板中字段的值
                message.setText(text, true);
                // 将发送的内容赋值给MimeMessageHelper,后面的true表示内容解析成html
                // 如果您不想解析文本内容，可以使用false或者不添加这项
                FileSystemResource file;
                for (String s : files)// 添加附件
                {
                    // s = MimeUtility.encodeWord(s);
                    file = new FileSystemResource(new File(s));// 读取附件
                    message.addAttachment(s, file);// 向email中添加附件
                }
            }
        };
        try {
            mailSender.send(preparator);// 发送邮件
            logger.info(new Date() + ">>>发送邮件到" + getString(mailTo));
        } catch (MailException ex) {
            logger.error("发送邮件失败" + ex.getMessage());
        }

    }

    public String getString(String[] mailTo) {
        StringBuilder sb = new StringBuilder();
        for (String mail : mailTo) {
            sb.append(mail);
        }
        return sb.toString();
    }

    private Map<String, Object> putTool(Map<String, Object> map) {
        // TODO
        map.put("date", new DateTool());
        return map;
    }

}